package org.momo.rpc.loadbalance.impl;

import org.momo.rpc.loadbalance.LoadBalancer;
import org.momo.rpc.protocol.RpcRequest;
import org.momo.rpc.provider.model.ProviderRegistryInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class PollingLoadBalancer implements LoadBalancer {

    private List<ProviderRegistryInfo> possibleServiceList;

    private int identityHashCode = 0;

    private final AtomicInteger currentIndex = new AtomicInteger(0);

    @Override
    public ProviderRegistryInfo loadBalance(RpcRequest request, List<ProviderRegistryInfo> possibleServiceList) {
        int identityHashCode = System.identityHashCode(possibleServiceList);
        if(identityHashCode != this.identityHashCode) {
            this.possibleServiceList = possibleServiceList;
            this.identityHashCode = identityHashCode;
        }
        int size = this.possibleServiceList.size();
        return this.possibleServiceList.get(currentIndex.incrementAndGet() % size);
    }


}
